<template>
    <div class="login">
        <h2>登录</h2>
        <form @submit.prevent>
            <div><input type="text" placeholder="用户名" v-model="userName"></div>
            <div><input type="password" placeholder="密码" v-model="password"></div>
            <button @click="login()" class="zc">登录</button>
        </form>
    </div>
</template>

<script setup>
import axios from 'axios'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const userName = ref('')
const password = ref('')

const router = useRouter()

const login = async () => {
    try {
        const res = await axios.get('http://127.0.0.1:3000/api/user/getAllUsers');
        const result = res.data.data.find((item) => {
            return item.username === userName.value && 
                   item.userpasswd === password.value && 
                   item.state === 1;
        });

        if (result) {
            // 动态获取用户ID字段（优先尝试常见字段名）
            const userIdField = ['id', 'userId', 'user_id', 'uid'].find(
                field => field in result
            );

            if (!userIdField) {
                throw new Error("接口未返回用户ID字段");
            }

            const userId = result[userIdField];
            
            // 存储用户名和用户ID
            sessionStorage.setItem('userName', userName.value);
            sessionStorage.setItem('userId', userId);
            
            alert('登录成功');
            router.push("/home");
        } else {
            const userExists = res.data.data.some(item => item.username === userName.value);
            if (userExists) {
                alert('您的账号已被禁用，请联系管理员');
            } else {
                alert('用户名或密码错误');
            }
        }
    } catch (error) {
        console.error('登录请求失败:', error);
        alert(error.message || '登录请求失败，请稍后重试');
    }
};
</script>
<style>
html{
    background-image: url('../assets/images/bj.png');
    background-size: cover; /* 使背景图片覆盖整个容器 */
    background-repeat: no-repeat; /* 防止背景图片重复 */
    
}
.login {
    width: 360px;
    height: 300px;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background: #ffffff;
    position: absolute; /* 绝对定位 */
    top: 150px; /* 向下移动 */
    right:350px; /* 向右移动 */
    

}

/*标题样式*/
h2 {
    font-size: 18px;
    color: #666;
    font-weight: bold;
    
}
/*表单输入框样式*/
form div {
    margin-bottom: 15px;
}

input[type="text"],
input[type="password"] {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-sizing: border-box;
}
/*按钮样式*/
.zc {
    width: 100%;
    padding: 10px;
    background-color: #F10180;
    color: white;
    border: none;
    
    cursor: pointer;
    font-size: 16px;
    margin-top:10px
    
}

button:hover {
    background-color: #218838;
}
</style>